﻿using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Kernel.Util;
using Alipay.EasySDK.Payment.FaceToFace.Models;
using Alipay.EasySDK.Payment.Page.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace Acme.ShopStore.Pay
{
    public class ALiPayAppService : ApplicationService, IALiPayAppService
    {
        private readonly IHttpContextAccessor _contextAccessor;

        public ALiPayAppService(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
        [HttpGet]
        //直接测试用地址,记得改订单信息. https://localhost:44341/api/app/a-li-pay/pay?Subject=test1&outTradeNo=111111111112&totalAmount=500
        public async void Pay(PayDto dto)
        {
            #region 1. 设置参数（全局只需设置一次）
            var config = new Config()
            {
                Protocol = "https",
                GatewayHost = "openapi.alipaydev.com",//"openapi.alipay.com",沙箱
                SignType = "RSA2",
                AppId = "2021000118635980",
                //请填写您的应用私钥
                MerchantPrivateKey = "MIIEowIBAAKCAQEApSJ5ZHACYBu4X7z91BiXg4opZNqatgooKd4P7biFTlkaQKuprYZcOH56KMdk4PrmjTtkSNHKB4TBsNZW6eghDQ3T/I+iAJ0nJUVUWSYl6TVg/gjWYM+2zNWwb9RHzGXxl1g2ini8JFrrjQt60naYTe2lzBmC0QdC8MEbS5JOafk4BkNWLAf+WONwHz/1ESk9JaCHuA4A2QDzq7kRTbtswFDIpJcHR7XPcjASKON7RpmHOGzQ2ZRKQ/6X+bSnEg5oHr67JAKC+AI/PHX5NpGpARRvKxZNWl2l8/qz+KkEnpISieV3ln3DN1GKhGpWDbFzPiQZgX3uqfjXB3/5jh1gGQIDAQABAoIBAEFquMArByXflViH293rqAn574/+cY9v0p1TVOgNUvHIpne8CUmuklXm9Km246WkfzSvtHiMcwYrdzeAkYmz5XPwaGwC0mB/4QQIxPNUA2yxMq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vi2yRN9zJvaHWnzDzYShxvYMQy1ux22zUOKWdQoiWgWe2/",
                //支付宝公钥
                AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyurwenQ4yAAZcvoOdU2SXiSbcjHpW163bCg43p5/Cqds07BJVgvAtNeFqZbqTSu2dgydydOCg64BS7qUl6XC+1+fxqTipfd16QHMpaFUCxAxlDmC1FIiTNo6AuvwdXM+3MhJyaWibH8D8CtVzytgVAxsPeOICiEsujZ2XHs8XuER4CjMMDZjr27ympmyGvAGanZBbDPa+Mhri3S8g21MWtnACIj+QmWpmYcGdEApZvlMK96upFdQm2P52jrHKdyQn1BsCZb1XH9OlhC3OP2kA6K4gpA7H+qKmn2su5Nt4WllL2tSy2eqtiP/LIg+bwDJoIJFi8dA02jY+y7n2bIvJQIDAQAB",
                //异步回调地址
                //NotifyUrl = "https://localhost:44341/api/app/a-li-pay/notify-url",
            };
            Factory.SetOptions(config);
            #endregion
            try
            {
                // 2. 发起API调用（以创建当面付收款二维码为例）
                //TODO:实训标题和订单号及金额是从dto中取得
                AlipayTradePagePayResponse response = Factory.Payment.Page().Pay(dto.Subject, dto.outTradeNo, dto.totalAmount, "https://localhost:44341/api/app/a-li-pay/return-url");
                // 3. 处理响应或异常
                if (ResponseChecker.Success(response))
                {
                    //把返回的html直接变成网页显示
                    var data = Encoding.UTF8.GetBytes(response.Body);
                    _contextAccessor.HttpContext.Response.ContentType = "text/html";
                    await _contextAccessor.HttpContext.Response.Body.WriteAsync(data, 0, data.Length);
                }
                else
                {
                    Console.WriteLine("调用失败，原因：" + response.Body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("调用遭遇异常，原因：" + ex.Message);


            }
        }
        [HttpGet]
        public string ReturnUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //if()先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update

                return "success";
            }
            return "";
        }
        [HttpGet]
        public string NotifyUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update
                //再循环返回库存
                //update


                return "success";
            }
            return "";
        }
    }
}